<?php

namespace App\Helpers\Lib;

use App\Exceptions\DaoException;
use App\Helpers\ResponseEnum;
use App\Models\TongUser;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class WechatMini
{
    protected static $appid = 'wx7d18bd50f621bf1c';

    protected static $secret = '7ba6d0de97c483d7926dbf363372181b';


    protected static $accessKey = 'tongxiansheng_mini_other';

    protected static $client = null;
    /**
     * 获取请求的实力对象
     * @return Client
     */
    protected static function getClientObj(){
        if (is_null(self::$client)){
            $client = new Client([
                // Base URI is used with relative requests
                //'base_uri' => 'https://api.weixin.qq.com',
                'base_uri' => 'https://api.weixin.qq.com',
                // You can set any number of default request options.
                'timeout'  => 2.0,
            ]);
            self::$client = $client;
            return $client;
        }else{
            return self::$client;
        }

    }


    /**
     * @param $data
     * @return mixed
     * @throws DaoException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function getMiniPic($data){
        //获取用户信息
        $userInfo = TongUser::query()->where('id',$data['u_id'])->first();
        $access_token= Cache::store('redis')->get(self::$accessKey);
        $client = self::getClientObj();
        $response = $client->post('/wxa/getwxacodeunlimit?access_token='.$access_token,[
            'headers' => [
                'Content-Type' => 'application/json',
                // 其他需要的头部信息
            ],
            'debug' => false,

            'json'=>[
                "page"=>'pages/login/reg',
                "scene"=>$userInfo['share_code'],
                "check_path"=>false,
                //"env_version"=>"trial",
                "env_version"=>"release",//打开正式版本
            ]
        ]);
        //$code = $response->getStatusCode();
       // var_dump($code);
        $body = $response->getBody();
        $body =  (string)$body;
        $body_arr = json_decode($body,true);
        if(checkIsHasField($body_arr,'errcode')){
            Log::warning('获取accessToekn失败',$body_arr);
            throw new DaoException(ResponseEnum::HTTP_ERROR,'qqq');
        }
        $img_url = '/public/images/'.$userInfo['mobile'].$userInfo['id'].'release'.'.jpg';
        Storage::put($img_url, $body, 'public');
        return '/images/'.$userInfo['mobile'].$userInfo['id'].'release'.'.jpg';
        // Implicitly cast the body to a string and echo it
        //return $body;
    }

    /**
     * 获取接口的调用凭证
     * @return void
     */
    public static function getAccessToken(){
        $client = self::getClientObj();
        $response = $client->request('GET', '/cgi-bin/token', ['query' => [
            'appid'=>self::$appid,
            'secret'=>self::$secret,
            'grant_type'=>'client_credential'
        ]]);

        $body = $response->getBody();
        // Implicitly cast the body to a string and echo it
        $body_arr = json_decode($body,true);
        if(checkIsHasField($body_arr,'errcode')){
            Log::warning('获取accessToekn失败',$body_arr);
            throw new DaoException(ResponseEnum::HTTP_ERROR,'获取accessToken失败');
        }
        //将token存储起来
        Cache::store('redis')->put(self::$accessKey,$body_arr['access_token']);
    }

    /**
     * @param $code
     * @return mixed
     * @throws DaoException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function getOpenId($code)
    {
        $client = self::getClientObj();
        $response = $client->request('GET', '/sns/jscode2session', ['query' => [
            'appid'=>self::$appid,
            'secret'=>self::$secret,
            'js_code'=>$code,
            'grant_type'=>'authorization_code'
        ]]);
        $code = $response->getStatusCode(); // 200
        $body = $response->getBody();
        // Implicitly cast the body to a string and echo it
        $body_arr = json_decode($body,true);
        if(checkIsHasField($body_arr,'errcode')){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'获取openid失败');
        }
        return $body_arr['openid'];

    }


    /**
     * 获取小程序支持的快递公司
     * @return void
     */
    public static function getDelivery(){
        $client = self::getClientObj();
        $access_token= Cache::store('redis')->get(self::$accessKey);
        $response = $client->request('GET', '/cgi-bin/express/business/delivery/getall', ['query' => [
            'access_token'=>$access_token,
        ]]);
        $code = $response->getStatusCode(); // 200
        $body = $response->getBody();
        // Implicitly cast the body to a string and echo it
        $body_arr = json_decode($body,true);
        if(checkIsHasField($body_arr,'errcode')){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'获取openid失败');
        }
        return $body_arr['data'];
    }

    /**
     * 订单发货调用生成运单
     * @return void
     */
    public static function createExpressOrder($order_info = []){
        $access_token= Cache::store('redis')->get(self::$accessKey);
        $client = self::getClientObj();
        $response = $client->post('/cgi-bin/express/business/order/add?access_token='.$access_token,[
            'headers' => [
                'Content-Type' => 'application/json',
                // 其他需要的头部信息
            ],
            'debug' => true,

            'json'=>[
                "order_id"=>makeOrderNo(), //订单id保证唯一
                'openid'=>'oHjii69Rtrq6CFp2f7Mml7UHWXl4',
                'delivery_id'=>'SF',
                'biz_id'=>'123456',
                'add_source'=>0,
                "custom_remark"=>'易碎物品',

                //发货人信息
                'sender'=>[
                    "name"=>"张三",
                    "tel"=>"020-88888888",
                    "mobile"=>"18666666666",
                    "company"=>"公司名",
                    "post_code"=>"123456",
                    "country"=>"中国",
                    "province"=>"广东省",
                    "city"=>"广州市",
                    "area"=>"海珠区",
                    "address"=>"XX路XX号XX大厦XX栋XX",
                ],
                'receiver'=>[
                    "name"=>"王小蒙",
                    "tel"=>"020-77777777",
                    "mobile"=>"18610000000",
                    "company"=>"公司名",
                    "post_code"=>"654321",
                    "country"=>"中国",
                    "province"=>"广东省",
                    "city"=>"广州市",
                    "area"=>"天河区",
                    "address"=>"XX路XX号XX大厦XX栋XX"
                ],
                //商品信息
                'shop'=>[
                    "wxa_path"=>"/index/index?from=waybill&id=01234567890123456789",
                    "detail_list"=>[
                      [
                          "goods_name"=>"微信气泡狗抱枕（小号）",
                          "goods_img_url"=>"https://mmbiz.qpic.cn/mmbiz_png/OiaFLUqewuIDNQnTiaCInIG8ibdosYHhQHPbXJUrqYSNIcBL60vo4LIjlcoNG1QPkeH5GWWEB41Ny895CokeAah8A/640",
                          "goods_desc"=>"40cm * 40cm尺寸"
                      ]
                    ]
                ],
                'cargo'=>[
                    'detail_list'=>[
                        'name'=>'微信气泡狗抱枕（小号）',
                        'count'=>'1'
                    ],
                ],
                "insured"=>[
                    "use_insured"=>1,
                    "insured_value"=>10000
                ],
                'service'=>[
                    'service_type'=>0,
                    'service_name'=>'标准快递'
                ]
            ]
        ]);
        //$code = $response->getStatusCode();
        // var_dump($code);
        $body = $response->getBody();
        $body =  (string)$body;
        $body_arr = json_decode($body,true);
        dd($body_arr);
        if(checkIsHasField($body_arr,'errcode')){
            Log::warning('获取accessToekn失败',$body_arr);
            throw new DaoException(ResponseEnum::HTTP_ERROR,$body_arr['errmsg']);
        }
        dd($body_arr);
    }
}
